<?php

use Nette\Security as NS;
/**
 * Trida slouzi pro overeni uzivatele pri prihlaseni.
 *
 * @author David Dusek
 */
class Authenticator extends Nette\Object implements NS\IAuthenticator {
    private $usersRep;

    public function __construct(\Doctrine\ORM\EntityRepository $usersRep)
    {
        $this->usersRep = $usersRep;
    }
    
    /**
     * Prihlaseni uzivatele. Overuje se uzivatelske jmeno a heslo. V pripade
     * chybnych prihlasovacich udaju je vyvolana vyjimka.
     * @param array $credentials uzivatelske jmeno a heslo (username, password)
     * @return Nette\Security\Identity vraci objekt identity uzivatele
     * @throws Nette\Security\AuthenticationException
     */
    function authenticate(array $credentials) {
        list($username, $password) = $credentials;
        
        $user = $this->usersRep->findOneBy(array("username" => $username));
        
        $dictionary = \CMS\Dictionary::getInstance();
        if ($user === null) {
            
            throw new NS\AuthenticationException($dictionary->translate("user_loginBadUsername"), 
                    self::IDENTITY_NOT_FOUND);
        }
        
        $pass = sha1(substr($username, -3) . $password);
        if ($user->password !== $pass) {
            throw new NS\AuthenticationException($dictionary->translate("user_loginBadPassword"), 
                    self::PASSWORD);
        }
        
        $identity = new NS\Identity($user->id, $user->group->name, 
                                    array("lang" => $user->language));
        
        return $identity;
                
    }
}
